package com.justnow.solution;


public class    Solution1 {

    /**
     * 第一种，我的写法，要强调的是现在的问题是和厉害的啦
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode combine = new ListNode(-1);
        ListNode head = combine;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                combine.next = new ListNode(l1.val);
                l1 = l1.next;
            } else {
                combine.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            combine = combine.next;
        }
        if (l1 != null) {
            combine.next = l1;
        }
        if (l2 != null) {
            combine.next = l2;
        }
        return head.next;
    }

    /**
     * leetcode官方解法
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeListNode(ListNode l1, ListNode l2) {
        ListNode prehead = new ListNode(-1);
        ListNode combine = prehead;
        while(l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                combine.next = l1;
                l1 = l1.next;
            } else {
                combine.next = l2;
                l2 = l2.next;
            }
            combine = combine.next;
        }
        // 合并后l1和l2最多只有一个还未被合并完，我们直接将链表末尾指向未合并完的链表即可
        combine.next = l1 == null ? l2 : l1;
        return prehead.next;
    }
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l11 = new ListNode(2);
        ListNode l12 = new ListNode(4);
        l1.next = l11;
        l11.next = l12;

        ListNode l2 = new ListNode(1);
        ListNode l21 = new ListNode(3);
        ListNode l22 = new ListNode(4);
        l2.next = l21;
        l21.next = l22;

        Solution1 solution1 = new Solution1();
        ListNode listNode = solution1.mergeTwoLists(l1, l2);

    }
}

class ListNode {
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}
